/*
 * ParseTool.cpp
 *
 *  Created on: 2012. 10. 16.
 *      Author: dalxx
 */

#include "ParseTool.h"
#include <Arduino.h>
//#undef SERIAL_TRACE_ON

namespace PLCLib {
unsigned long ParseTool::time_out=100;
const char* ParseTool::whiteSpace=" ,\t\r\n";
char* ParseTool::lineSeperator=";";


int ParseTool::eatWhite(Stream& stream) {
	int i, ch=0;


//#ifdef  SERIAL_TRACE_ON
//		Serial.print("EatWhite available: ");	Serial.print(stream.available());
//
//		Serial.println();
//#endif


	for(i=0;ch!=-1;i++)
	{
		ch=ParseTool::timedPeek(stream);
//#ifdef  SERIAL_TRACE_ON
//		Serial.print("EatWhite peek:");	Serial.print(ch);Serial.print("-");Serial.print((char)ch);
//		Serial.print(", EatWhite stream: ");	Serial.print((int)strchr(ParseTool::whiteSpace,ch));
//		Serial.println();
//#endif
		if(strchr(ParseTool::whiteSpace, ch)!=NULL)
			ParseTool::timedRead(stream);
		else break;
	}
	return i;
}

int ParseTool::timedRead(Stream& stream) {
	int c;
	unsigned long _startMillis = millis();
	do {
	   c = stream.read();
	    if (c >= 0) return c;
	  } while(millis() - _startMillis < ParseTool::time_out);
	  return -1;     // -1 indicates timeout
}

int ParseTool::timedPeek(Stream& stream) {
	int c;
		int _startMillis = millis();
		do {
		   c = stream.peek();
		    if (c >= 0) return c;
		  } while(millis() - _startMillis < ParseTool::time_out);

	  return -1;     // -1 indicates timeout
}



} /* namespace PLCLib */


